package com.gdca.sdk.ca.utils;

import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.util.Base64;
import android.util.Log;

import com.gdca.sdk.ca.SdkManager;
import com.gdca.sdk.ca.listener.RequestCallBack;
import com.gdca.sdk.ca.model.ResultModel;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by Dell on 2017/4/11.
 */

public class NetworkUtil {
    public final static int RESULT_EXCEPTION = -1;
    public final static int RESULT_SUCCESS = 1;
    public final static int RESULT_FAIL_ID = 2;

    private final String AUTHSECRET = "hPVjPd0IKAmh8T0lOh4T824NeEMzLkDpJ2J2bZhUg22KnSOTGsrjFm4wlImpoQrZ";
    private final String AUTHCODE = "5YxYiu6pW5YKAa2O";
    private final String url = "http://192.168.10.114:8088/signofcloud-web-app/api/v1/sdk/getSignInfo";
    public static String PATH = "http://192.168.10.121:8091/api/v1/";
//    public static String PATH = "http://192.168.22.250:8080/gateway/api/v1/";



    public static boolean networkConnected(Context context) {
        if (context != null) {
            ConnectivityManager manager = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
            NetworkInfo info = manager.getActiveNetworkInfo();
            if (info != null)
                return info.isAvailable();
        }

        return false;
    }

    public static void checkSdk(final Context context, final RequestCallBack callBack) throws JSONException {
        String url = PATH + "sdk/sdkValidate";
        JSONObject data = new JSONObject();
        data.put("packageName", context.getPackageName());
        if (data.toString().length() == 0) {
            return;
        }
        final String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP);
        JSONObject object = dataFormat(System.currentTimeMillis() + DeviceInfo.getDeviceId(context), dataStr);
        OkHttpUtils.getInstance().doPostString(context, url, object.toString(), false, callBack);
    }

    public static void requestBind(final Context context, String userBusId, String accountName, String notifyUrl, final RequestCallBack callBack) throws JSONException {
        String url = PATH + "caBind/generateAppTask";
        JSONObject data = new JSONObject();
        data.put("userBusId", userBusId);
        data.put("accountName", accountName);
        data.put("notifyUrl", notifyUrl);
        final String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP);
        JSONObject object = dataFormat(System.currentTimeMillis() + DeviceInfo.getDeviceId(context), dataStr);
        OkHttpUtils.getInstance().doPostString(context, url, object.toString(), false, callBack);
    }

    public static void requestLogin(Context context, String notifyUrl, final RequestCallBack callBack) throws JSONException {
        String url = PATH + "caLogin/generateAppTask";
        JSONObject data = new JSONObject();
        data.put("notifyUrl", notifyUrl);
        final String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP);
        JSONObject object = dataFormat(System.currentTimeMillis() + DeviceInfo.getDeviceId(context), dataStr);
        OkHttpUtils.getInstance().doPostString(context, url, object.toString(), false, callBack);
    }

    public static void getBindResult(Context context, long signTaskId, RequestCallBack callBack) throws JSONException {
        String url = PATH + "caBind/queryProgress";
        JSONObject data = new JSONObject();
        data.put("signTaskId", signTaskId);
        final String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP);
        JSONObject object = dataFormat(System.currentTimeMillis() + DeviceInfo.getDeviceId(context), dataStr);
        OkHttpUtils.getInstance().doPostString(context, url, object.toString(), false, callBack);
    }

    public static void getLoginResult(Context context, long signTaskId, RequestCallBack callBack) throws JSONException {
        String url = PATH + "caLogin/queryProgress";
        JSONObject data = new JSONObject();
        data.put("signTaskId", signTaskId);
        final String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.NO_WRAP);
        JSONObject object = dataFormat(System.currentTimeMillis() + DeviceInfo.getDeviceId(context), dataStr);
        OkHttpUtils.getInstance().doPostString(context, url, object.toString(), false, callBack);
    }

    public void requestSignResult(Context context, String id, final String token, final ResultCallBack callBack) {
        try {
            JSONObject data = new JSONObject();
            data.put("signId", id);
            String dataStr = Base64.encodeToString(data.toString().getBytes(), Base64.DEFAULT);
            JSONObject object = dataFormat(token, "", dataStr);
            OkGo.post(url)
                    .tag(context)
                    .upJson(object)
                    .execute(new StringCallback() {
                        @Override
                        public void onSuccess(String s, Call call, Response response) {
                            try {
                                JSONObject object = new JSONObject(s);
                                int code = object.optInt("code", -1);
                                String message = object.optString("message");
                                if (code == 0) {
                                    JSONObject coObject = object.optJSONObject("content");
                                    long id = coObject.optLong("signId", 0);
                                    String pubKey = coObject.optString("pubKey");
                                    int status = coObject.optInt("signStatus", 1);
                                    int result = coObject.optInt("signResult", 0);
                                    ResultModel model = new ResultModel(id, pubKey);
                                    model.setResult(result);
                                    model.setStatus(status);
                                    if (callBack != null) {
                                        callBack.onSuccess(model);
                                    }
                                } else {
                                    if (callBack != null) {
                                        callBack.onFail(message, code);
                                    }
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }

                        }

                        @Override
                        public void onError(Call call, Response response, Exception e) {
                            super.onError(call, response, e);
                            e.printStackTrace();
                            Log.e("1111111", "onError : " + response.code());
                            if (callBack != null) {
                                callBack.onFail(response.message(), response.code());
                            }
                        }
                    });
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private JSONObject dataFormat(String token, String bussNo, String dataStr) throws JSONException {
        JSONObject object = new JSONObject();
        String timestamp = String.valueOf(System.currentTimeMillis());
        object.put("timestamp", timestamp);
        object.put("bussNo", bussNo);
        object.put("token", token);
        object.put("authCode", AUTHCODE);
        object.put("data", dataStr);

        StringBuilder signInfo = new StringBuilder();
        signInfo.append("authCode=").append(AUTHCODE);
        if (bussNo != null && bussNo.length() > 0) {
            signInfo.append("&bussNo=").append(bussNo);
        }
        signInfo.append("&data=").append(dataStr).append("&timestamp=").append(timestamp).append("&token=").append(token).append("&key=").append(AUTHSECRET);
        object.put("signInfo", EncryptUtils.encryptSHA256ToString(signInfo.toString().getBytes()));
        return object;
    }

    private static JSONObject dataFormat(String bussNo, String dataStr) throws JSONException {
        JSONObject object = new JSONObject();
        String timestamp = String.valueOf(System.currentTimeMillis());
        object.put("timestamp", timestamp);
        object.put("bussNo", bussNo);
        object.put("app_id", SdkManager.app_id);
        object.put("data", dataStr);
        StringBuilder signInfo = new StringBuilder();
        signInfo.append("app_id=").append(SdkManager.app_id);
        if (bussNo != null && bussNo.length() > 0) {
            signInfo.append("&bussNo=").append(bussNo);
        }
        signInfo.append("&data=").append(dataStr).append("&timestamp=").append(timestamp).append("&app_secret=").append(SdkManager.app_secret);
        object.put("signInfo", EncryptUtils.encryptSHA256ToString(signInfo.toString().getBytes()));
        return object;
    }

    public interface ResultCallBack {
        void onSuccess(Object o);

        void onFail(String message, int code);
    }
}
